<template>
  <q-input class="search-user no-shadow q-mb-md" :loading="loading" inverted-light color="grey-2" v-model="key" :placeholder="placeholder">
    <q-popover v-model="autocomplete" fit>
      <q-list v-if="querySet && querySet.length > 0" separator link>
        <q-item v-for="instance in querySet.slice(0, 5)" :key="instance.id" v-close-overlay @click.native="add(instance)">
          <q-item-side class="row items-center"><a-head :user="instance" :size="24" :username="false"></a-head></q-item-side>
          <q-item-main>{{ instance.username }}</q-item-main>
          <q-item-side right><q-icon name="add"/></q-item-side>
        </q-item>
      </q-list>
    </q-popover>
  </q-input>
</template>

<script>
    export default {
      name: 'aSearchUser',
      props: {
        placeholder: {
          type: String,
          required: false,
          default: '请搜索用户名'
        }
      },
      data () {
        return {
          key: '',
          autocomplete: false,
          querySet: null,
          width: null,
          loading: false
        }
      },
      computed: {

      },
      watch: {
        async key(key){
          if (key.length < 2) {
            this.querySet = null
            return
          }
          this.loading = true
          await this.getQuerySet({
            api: '/api/user/search_users/',
            params: {
              username: key
            }
          })

          this.loading = false
          this.autocomplete = true
        }
      },
      methods: {
        add(instance){
          this.$emit('add', instance)
          this.key = ''
        }
      }
    }
</script>

<style lang="stylus">
  @import '~variables'
  .search-user
    //
</style>
